var util = require('../../utils/util');
var wxApi = require('../../utils/wxApi');
var wxRequest = require('../../utils/wxRequest');
import config from '../../utils/config';
import { $wuxCountDown } from '../../components/wux'

var app = getApp();
var that;

var inputContent = {};
 
Page({
  data: {
    user: {}
    ,prevPage:null
    ,istb:true
    ,items: [
      {value: 'lz', name: '柳州', checked: true },
      {value: 'gl', name: '桂林'},
      {value: 'nn', name: '南宁'},
      {value: 'qt', name: '其他'}
        //,{value: 'test', name: '测试'}
    ]
    ,yzm:{data:"",date:null}
    ,blyzm:true
    ,blreg:true
    ,regtext:"绑定DK账号"
    ,btntxt:"注册DK账号"
    ,sheight:450
    ,sheight2:450*0.2
      ,back:0
  },
  onLoad: function (options) {
    that = this;
    wx.setNavigationBarTitle( { title: "同步/注册账号" });

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sheight: res.windowHeight,
          sheight2:res.windowHeight *0.2
        })
      }
    })

    if( !util.judge.isNull(options.back) ){
        that.data.back = parseInt(options.back);
    }

    that.loadData();
  },
  onReady: function () {
    wx.setNavigationBarTitle( { title: "同步账号" });
    that.isload = false;
  },
  onShareAppMessage: function () {
      return app.getShare();
  },
  loadData:function(options){
    util.showLoading();
    
    var pages = getCurrentPages();
    that.data.prevPage = pages[pages.length - 2];
    var user = null;
    that.setData({
      user:that.data.prevPage.data.user
    });

    
    
    inputContent["city"]="lz";
    util.hideLoading();

  }

    ,btnGetkb2:function(){
        setTimeout(this.btnGetkb,300);
    }
  //提交
  ,btnGetkb:function(){
      var cate = "zc";

      var xm = inputContent["xm"];
      var dlm = inputContent["dlm"];
      var mm = inputContent["mm"];
      var mm2 = inputContent["mm2"];

      if(that.data.istb){
          cate ="tb";
      }else
      {
          if(!util.judge.isString(xm)){
              util.alert("请输入您的姓名");
              return false;
          }

          if(!util.judge.isString(dlm)){
              util.alert("请输入登录名");
              return false;
          }

          if(!util.judge.isString(mm)){
              util.alert("请输入密码");
              return false;
          }

          if(mm.length < 6 || mm.length > 12){
              util.alert("密码长度为6-12位");
              return false;
          }

          if(mm != mm2){
              util.alert("两次密码输入不正确，请查证!");
              return false;
          }

          if(/^[a-zA-Z0-9]+$/.test(dlm) == false){
              util.alert("登录名应为英文+数字，请查证!");
              return false;
          }
          if(/^[a-zA-Z0-9]+$/.test(mm) == false){
              util.alert("密码应为英文+数字，请查证!");
              return false;
          }
      }

    var phone = inputContent["phone"];
    var bl = that.checkMobile(phone);
    
    if(!bl){
      util.alert("请输入正确的手机号码");
      return false;
    }

    var yzm = inputContent["yzm"];
    if(!yzm || yzm.length != 6 ){
      util.alert("请输入6位验证码");
      return false;
    }
    
    var city = inputContent["city"];

    util.showLoading();

    var url = config.url_user_check_yzm;
    var params = {
        city:city,
        yzm:yzm,
        phone:phone,
        cate:cate,
        xm:xm,
        dlm:dlm,
        mm:mm
    };

    //wxRequest.postRequest(url, params)
    //.then(res => {
    //    console.log(res);
    //    var data = res;
    //    if(data != 1){
    //      util.alert("验证码错误,请查证!");
    //        throw util.stop();
    //    };

    //    var url = config.url_user_save_zc;
    //    return wxRequest.postRequest(url, params);
      //})

    url = config.url_user_save_zc;
    wxRequest.postRequest(url, params)
    .then(res => {
      console.log(res);
        var data = res;

        if(data == "24"){
            util.alert("该手机号已经绑定了小程序，不能再次绑定!");
            return false;
        }

        if(data == "31"){
            util.alert("验证码错误，请查证!");
            return false;
        }

        if(data == "32"){
            util.alert("该手机号已被注册，请查证!");
            return false;
        }

        if(data == "25"){
            if(cate=="tb"){
                util.alert("手机号对应的DK账号不存在，请查证或注册新账号!");
            }else{
                util.alert("新账号注册失败，请稍后重试!");
            }
            return false;
        }

        if(data == "26"){
            util.alert("该手机号已经绑定小程序，不能再次绑定!");
            return false;
        }

        if(data == "28"){
            util.alert("账号所属城市信息错误，请稍后重试!");
            return false;
        }

        if(!util.judge.isObject(data)){
            util.alert("数据读取失败，请重试!");
          return false;
        }

        //注册或者同步成功 
        var kbnow = res.kbnow;
        var kbxf = res.kbxf;
        var isnew = res.isnew;
         
        //这个时候 要调用上个页面的对象 进行同步
        app.globalData.user.isgl = 1;
       
        that.data.prevPage.setData({
          isgl:true,
          'kbobj.kbxf':kbxf,
          'kbobj.kb':kbnow
        });

        if(that.data.back ==1){
            util.alert("保存成功!",function(){
                wx.redirectTo({
                    url: '../user/dayhis'
                });
            });
        }else{
            var str ="同步成功，快去领取Kb吧";
            if(isnew == "1"){
                str="成功注册新用户，可用您的手机号作为用户名跟密码,登录DK账户，快去领取Kb吧!";
            }

            util.alert(str,function(){
                wx.navigateBack({
                    delta: 1
                })
            });
        }

    })
    .catch(res => {
        console.log(res);
        util.alert_catch(res);
    })
    .finally(function (res) {
        util.hideLoading();
    });

  }
  ,btnTbzh:function(){
    
  }
  ,bindChange: function(e) {
    inputContent[e.currentTarget.id] = e.detail.value
    // if(e.currentTarget.id =="yzm"){
    //   var val = e.detail.value;
    //   if(val.length==6){
    //     if(val == that.data.yzm.data){
    //       that.setData({
    //         blyzm:true
    //       });
    //       return;
    //     }
    //   }

    //   that.setData({
    //     blyzm:false
    //   });
    // }

  }
  ,
  radioChange: function(e) {
    inputContent[e.currentTarget.id] = e.detail.value
    var items = this.data.items;
    for (var i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value == e.detail.value
    }
    this.setData({
      items: items
    });
  }
  ,yzcode:function(){


  }
    ,vcode2:function(){
        setTimeout(this.vcode,300);
    }
  ,vcode() {
    if (that.c2 && that.c2.interval) return false;
    //业务判断
    var phone = inputContent["phone"];
    var bl = that.checkMobile(phone);
    
    // util.alert(bl.toString());
    if(!bl){
      util.alert("请输入正确的手机号码");
      return false;
    }
    var city = inputContent["city"];
    // util.alert(city);
    // return false;
    //读取接口获取验证码
    //
     
    util.showLoading();

    var url = config.url_user_get_phone_isgl;
    var params = {
      city:city,
      phone:phone
    };
    wxRequest.postRequest(url, params)
    .then(res => {
        console.log(res);
        var data = res;
        //判断是否已经同步火注册了,这里是个控制判断
            
        var url = config.url_user_get_yzm;
        var params = {
          city:city,
          phone:phone
        };
        return wxRequest.postRequest(url, params);
    })
    .then(res => {
        console.log(res);
        if(res != 1){
            util.alert("验证码获取失败，请稍后重试");
          return false;
        }else{
          util.showToast("验证码已成功发送");
        }
        //得空了验证码的相关内容
        // that.data.yzm.data=res.yzm;
        // that.data.yzm.date=res.qxdate;

        that.c2 = new $wuxCountDown({
          date: +(new Date) + 60000, 
          onEnd() {
            that.setData({
              c2: '获取验证码', 
            })
          },
          render(date) {
            const sec = this.leadingZeros(date.sec, 2)  + ' 秒 '
            date.sec !== 0 && that.setData({
              c2: sec, 
            })
          },
        })

    })
    .catch(res => {
        console.log(res);
        util.alert(res.message);
    })
    .finally(function (res) {
        util.hideLoading();
    });

  },
  checkMobile :function (str) {
    var re = /^1[34578]\d{9}$/;
    if (re.test(str)) {
      return true;
        //alert("正确");
    } else {
      return false;
    }
  },
  btnSetcz:function(e){

    var istb =true;
    var regtext ="绑定已有的DK账号";
    var btntxt = "注册DK账号";
    if(that.data.istb == true ){
      istb = false;
      regtext="注册DK账号";
      btntxt = "绑定已有的DK账号";
    }else{
      istb =true;
      regtext ="绑定已有的DK账号";
      btntxt = "注册DK账号";
    }
    that.setData({
      blreg:false
      ,istb:istb
      ,regtext:regtext
      ,btntxt:btntxt
    });


  }

})